package com.coder.rental.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.User;
import com.coder.rental.service.IRoleService;
import com.coder.rental.service.IUserService;
import com.coder.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 权限_用户管理 前端控制器
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@RestController
@RequestMapping("/rental/user")
public class UserController {
    /**
     * 获取所有用户
     * 返回结果包装成Result
     */
    @Resource
    private IUserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private IRoleService roleService;
    @GetMapping
    public Result<List<User>> list(){
        return Result.success(userService.list());
    }

    @PostMapping("{start}/{size}")
    public Result search(@PathVariable int start,@PathVariable int size,@RequestBody User user){
        return Result.success(userService.searchByPage(new Page<>(start,size), user));
    }
    @PostMapping
    public Result save(@RequestBody User user){
        User user1 = userService.selectByUsername(user.getUsername());
        if(user1!=null){
            return Result.fail().setMessage("用户名已存在");
        }else {
            // 密码加密
            user.setPassword("{bcrypt}"+passwordEncoder.encode(user.getPassword()));
            user.setIsAdmin(0);
            user.setAccountNonExpired(true);
            user.setAccountNonLocked(true);
            user.setCredentialsNonExpired(true);
            user.setEnabled(true);
            if(StrUtil.isEmpty(user.getAvatar())){
                user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            }
            return userService.save(user)?Result.success().setMessage("添加成功"):Result.fail().setMessage("添加失败");
        }
    }

    @PutMapping
    public Result update(@RequestBody User user){
        // 如果用户修改了用户名,不能与其他id的用户名重复
        User u = userService.selectByUsername(user.getUsername());
        if(u!=null&& !Objects.equals(u.getId(),user.getId())){
            return Result.fail().setMessage("用户名已存在");
        }

        // 设置默认头像
        if(StrUtil.isEmpty(user.getAvatar())){
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }
        return userService.updateById(user)?Result.success().setMessage("修改成功"):Result.fail().setMessage("修改失败");
    }
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        return userService.delete(ids)?Result.success().setMessage("删除成功"):Result.fail().setMessage("删除失败");
    }
    // 获取当前用户所绑定的角色id
    @GetMapping("role/{userId}")
    public Result selectRoleByUserId(@PathVariable Integer userId){
        return Result.success(roleService.selectRoleIdByUserId(userId));
    }
    @GetMapping("bind/{userId}/{roleIds}")
    public Result bindRole(@PathVariable Integer userId,@PathVariable String roleIds){
        List<Integer> list= Arrays.stream(roleIds.split(",")).map(Integer::parseInt).toList();
        if(list.isEmpty()){
            return Result.fail().setMessage("请选择角色");
        }
        // 设置属性默认值
        User user = userService.selectById(userId);
        user.setCredentialsNonExpired(true);
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setEnabled(true);

        return userService.bindRole(userId,list)?Result.success().setMessage("绑定成功"):Result.fail().setMessage("绑定失败");
    }
}
